<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>CURD</title>
    <link rel="stylesheet" href="./css/style.css">
    <style>
           /* 
            * 由于IE不支持<template>标签，所以template标签中的内容在IE下会直接显示出来。
            * 将模板设为隐藏即可解决这个问题，template标签各浏览器支持请参考：http://caniuse.com/#feat=template
            */
			#grid-template, #dialog-template{
				display: none;
            }
    </style>
</head>
<body>
    <div id="app" v-cloak>
        <div class="container">
            <div class="form-group">
                <form>
                    <label>输入框：</label>
                    <input type="text" class="search-input" v-model="searchQuery" placeholder="输入名字可筛选结果">
                </form>
            </div>
        </div>
        <div class="container">
            <simple-grid :data-List="people" :columns="columns" :search-Key="searchQuery"></simple-grid>
        </div>
    </div>

    <!--子组件simple-grid模板-->
    <template id="grid-template">
        <div> <!-- template只有一个根节点 -->
            <table>
                <thead>
                    <tr>
                        <th v-for='col in columns'>{{col.name}}</th>
                        <th>delete</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="(item,index) in filteredUsers">
                        <td v-for="col in columns">
                            <span v-if="col.isKey"><a href="javascript:void(0)" @click="openEditorItemDialog('Edit Item ')"> {{item[col.name]}}</a></span>                          
                            <span v-else>{{item[col.name]}}</span>
                        </td>
                        <td class="text-center"><button class="btn-danger" @click="deleteItem(item)">delete</button></td>
                    </tr>
                </tbody>
            </table> 
            <div class="container"><button class="btn" @click="openNewDialog('Create New Item')">create</button></div>
            <modal-dialog :mode="mode" :title="title" :fields="columns" :item="item" ref="dialogItem"  v-on:create-item="createItem" v-on:update-item="updateItem"></modal-dialog> 
        </div>
    </template> 



    <!--子组件modal-dialog模板-->
    <template id="dialog-template">
        <div class="dialogs">
            <div class="dialog" :class = "{ 'dialog-active': show}">
                <div class="dialog-content">
                    <header class="dialog-header">
                        <h1 class="dialog-title">{{ title }}</h1>
                        <!-- <span @click="close">X</span> -->
                    </header>
                    <div class="dialog-body">
                        <div v-for="field in fields" class="form-group">
                            <label>{{ field.name }}</label>
                            <select v-if="field.dataSource" v-model="item[field.name]" :disabled="mode === 2 && field.isKey">
                                <option v-for="opt in field.dataSource" :value="opt" >{{ opt }}</option>
                            </select>
                            <input v-else type="text" v-model="item[field.name]" :disabled="mode === 2 && field.isKey">
                        </div>
                    </div> 
                    <footer class="dialog-footer">
                        <div class="form-group">
                            <label></label>
                            <button class="btn-save" @click='save'>Save</button>
                            <button class="btn-close" @click="close">Close</button>
                        </div>
                    </footer>
                </div>
            </div>
            <div class="dialog-overlay"></div>       
        </div> 
    </template>

    <script src="./vue.js"></script>
    <script>
    // 全局注册simple-grid组件
     Vue.component('simple-grid',{
         template: '#grid-template',
         props:['dataList','columns','searchKey'],
         data: function() {
            return {
                mode: 0,
                item: {},
                keyColumn: '',
                title: ''
                
            }
         },
         methods:{
            openNewDialog: function(title) {
                this.title = title
                //新建模式，mode为1
                this.mode = 1
                this.item = {}
               //使用$refs，是父组件引用子组件
                this.$refs.dialogItem.show = true
            },
            openEditorItemDialog: function(key) {
                // 根据主键查找当前修改的数据
                // var currentItem = this.findItemByKey(key)
                // 对话框的标题
                this.title =  key
                // mode = 2表示修改模式
                this.mode = 2
                //使用$refs，是父组件引用子组件
                this.$refs.dialogItem.show = true
            },
            createItem: function(){
                // var  keyColumn = this.keyColumn
                // if(!this.itemExists(keyColumn)){
                    // 将item追加到dataList
                    this.dataList.push(this.item)
                    //重置item
                    this.item = {}
                // }else {
                //     alert(keyColumn + ' "' + this.item[keyColumn] + '" is already exists')
                // }

            },
            updateItem: function(){
                // 获取主键列
                var keyColumn = this.keyColumn
                for (var i = 0; i < this.dataList.length; i++) {
                    // 根据主键查找要修改的数据，然后将this.item数据更新到this.dataList[i]
                    if (this.dataList[i][keyColumn] === this.item[keyColumn]) {
                        for (var j in this.item) {
                            this.dataList[i][j] = this.item[j]
                        }
                        break;
                    }
                }
                this.item = {}
            },
            deleteItem: function(item) {
                var idx = this.dataList.indexOf(item)
                this.dataList.splice(idx,1)
            }
         },
         computed: {
             // 查询功能，含过滤操作，在输入框过滤名字结果
            filteredUsers: function () {
                var self = this
                return self.dataList.filter(function (user) {
                    return user.name.indexOf(self.searchKey) !== -1
                })
            }
         },
         components: {
            'modal-dialog': {
                template: '#dialog-template',
                data: function() {
                    return {
                        //模态框默认隐藏
                        show: false
                    }
                },
                props: ['mode','item','fields','title'],
                methods: {
                    close: function() {
                        this.show =  false
                    },
                    save: function() {
                        if(this.mode === 1){
                            this.show = false
                            this.$emit('create-item')    
                        }else if(this.mode === 2) {
                            this.show = false   
                            this.$emit('update-item')
                        }
                    }                  
                }

             }

         }
     }),

     new Vue({
         el: '#app',
         data: {
            searchQuery: '',
            columns:[{
                name: 'name',
                isKey: true
            },{
                name: 'age'
            },{
                name: 'sex',
                dataSource: ['Male','Female']
            }],
            people: [{
                name: 'Jack',
                age: 35,
                sex: 'Male'
            }, {
                name: 'Bill',
                age: 26,
                sex: 'Male'
            }, {
                name: 'Tracy',
                age: 22,
                sex: 'Female'
            }, {
                name: 'Chris',
                age: 36,
                sex: 'Male'
            }],
         }
     })
    
    </script>
</body>
</html>